package com.mall.controller;

import com.mall.pojo.CartItem;
import com.mall.pojo.Result;
import com.mall.pojo.goods;
import com.mall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/member/cart")
public class CartController {

    @Autowired
    private CartService cartService;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostMapping
    public ResponseEntity<String> addToCart(@RequestBody Map<String, Object> params,
                                           @RequestParam(value = "userId", required = false) Long userId) {
        try {
            // 获取前端传递的skuId和count值
            Long skuId = Long.parseLong(params.get("skuId").toString());
            Integer count = Integer.parseInt(params.get("count").toString());
            
            // 如果userId为null，尝试从请求参数中获取
            if (userId == null && params.containsKey("userId")) {
                userId = Long.parseLong(params.get("userId").toString());
            }
            
            if (userId == null) {
                return ResponseEntity.badRequest().body("添加失败: 用户ID不能为空");
            }
            
            System.out.println("添加购物车，用户ID: " + userId + ", skuId: " + skuId + ", count: " + count);
            
            // 检查商品是否存在
            try {
                System.out.println("正在查询商品ID: " + skuId + ", 类型: " + skuId.getClass().getName());
                
                // 尝试将Long转换为Integer范围内的值
                Integer skuIdInt = null;
                try {
                    skuIdInt = skuId.intValue();
                    System.out.println("转换后的商品ID(int): " + skuIdInt);
                } catch (Exception e) {
                    System.err.println("ID转换失败: " + e.getMessage());
                }
                
                // 使用Integer参数查询
                List<Map<String, Object>> goods = jdbcTemplate.queryForList(
                    "SELECT * FROM goods WHERE id = ?", skuIdInt);
                    
                if (goods.isEmpty()) {
                    System.out.println("商品不存在，skuId: " + skuId + ", intValue: " + skuIdInt);
                    return ResponseEntity.badRequest().body("添加失败: 商品不存在");
                } else {
                    System.out.println("商品存在: " + goods.get(0));
                }
            } catch (Exception e) {
                System.err.println("查询商品失败: " + e.getMessage());
                e.printStackTrace();
                return ResponseEntity.badRequest().body("添加失败: " + e.getMessage());
            }
            
            CartItem item = new CartItem();
            item.setUserId(userId);
            item.setSkuId(skuId);
            item.setCount(count);
            item.setSelected(true); // 默认选中
            
            // 直接使用JDBC添加购物车项
            try {
                // 检查是否已存在
                List<Map<String, Object>> existing = jdbcTemplate.queryForList(
                    "SELECT * FROM cart WHERE user_id = ? AND sku_id = ?", 
                    userId, skuId);
                
                if (!existing.isEmpty()) {
                    // 更新已有项目
                    jdbcTemplate.update(
                        "UPDATE cart SET count = count + ?, checked = 1, update_time = NOW() WHERE user_id = ? AND sku_id = ?",
                        count, userId, skuId);
                    System.out.println("更新已有购物车项目成功");
                } else {
                    // 插入新项目
                    jdbcTemplate.update(
                        "INSERT INTO cart (user_id, sku_id, count, checked) VALUES (?, ?, ?, 1)",
                        userId, skuId, count);
                    System.out.println("添加新购物车项目成功");
                }
                
                return ResponseEntity.ok("添加成功");
            } catch (Exception e) {
                System.err.println("JDBC添加购物车失败: " + e.getMessage());
                // 降级到使用MyBatis
                cartService.addToCart(item);
                return ResponseEntity.ok("添加成功 (MyBatis)");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("添加失败: " + e.getMessage());
        }
    }

    @GetMapping
    public Result getCartList(@RequestParam("userId") Long userId) {
        System.out.println("获取购物车列表，用户ID: " + userId);
        
        // 使用直接查询，不依赖于JOIN
        List<Map<String, Object>> cartItems = jdbcTemplate.queryForList(
            "SELECT * FROM cart WHERE user_id = ?", userId);
        
        if (cartItems.isEmpty()) {
            System.out.println("用户没有购物车数据");
            return Result.success(Collections.emptyList());
        }
        
        // 手动构建购物车项，不依赖JOIN查询
        List<CartItem> result = new ArrayList<>();
        for (Map<String, Object> item : cartItems) {
            CartItem cartItem = new CartItem();
            cartItem.setId(((Number)item.get("id")).longValue());
            cartItem.setUserId(((Number)item.get("user_id")).longValue());
            cartItem.setSkuId(((Number)item.get("sku_id")).longValue());
            cartItem.setCount((Integer)item.get("count"));
            cartItem.setSelected((Boolean)item.get("checked"));
            
            // 设置一些缺省值
            cartItem.setPrice(BigDecimal.valueOf(99)); // 设置默认价格
            cartItem.setName("商品 " + cartItem.getSkuId()); // 设置默认名称
            cartItem.setPicture("https://img.picui.cn/free/2025/03/20/67dbcea0b6f32.png"); // 设置默认图片
            cartItem.setCreateTime((LocalDateTime)item.get("create_time"));
            cartItem.setUpdateTime((LocalDateTime)item.get("update_time"));
            
            // 尝试查找商品信息
            try {
                // 转换为Integer
                Integer skuIdInt = null;
                try {
                    skuIdInt = cartItem.getSkuId().intValue();
                } catch (Exception e) {
                    System.err.println("购物车商品ID转换失败: " + e.getMessage());
                }
                
                if (skuIdInt != null) {
                    List<Map<String, Object>> goodsInfo = jdbcTemplate.queryForList(
                        "SELECT * FROM goods WHERE id = ?", skuIdInt);
                    
                    if (!goodsInfo.isEmpty()) {
                        Map<String, Object> goodsData = goodsInfo.get(0);
                        cartItem.setName((String)goodsData.get("name"));
                        cartItem.setPicture((String)goodsData.get("image"));
                        cartItem.setPrice(BigDecimal.valueOf(((Number)goodsData.get("price")).intValue()));
                        
                        // 创建一个goods对象
                        goods goodsObj = new goods();
                        goodsObj.setId((Integer)goodsData.get("id"));
                        goodsObj.setName((String)goodsData.get("name"));
                        goodsObj.setImage((String)goodsData.get("image"));
                        goodsObj.setPrice((Integer)goodsData.get("price"));
                        cartItem.setGoods(goodsObj);
                    } else {
                        System.out.println("没有找到商品信息: " + cartItem.getSkuId() + ", intValue: " + skuIdInt);
                    }
                } else {
                    System.out.println("跳过查询商品，ID无法转换: " + cartItem.getSkuId());
                }
            } catch (Exception e) {
                System.err.println("获取商品信息失败: " + e.getMessage());
            }
            
            result.add(cartItem);
        }
        
        System.out.println("手动构建了 " + result.size() + " 个购物车项");
        return Result.success(result);
    }
    
    // 调试端点：直接查询数据库中的购物车数据
    @GetMapping("/debug")
    public Result debugCart(@RequestParam("userId") Long userId) {
        // 查询购物车表
        List<Map<String, Object>> cartItems = jdbcTemplate.queryForList(
            "SELECT * FROM cart WHERE user_id = ?", userId);
        System.out.println("原始购物车数据: " + cartItems);
        
        // 查询用户表，检查ID类型
        List<Map<String, Object>> users = jdbcTemplate.queryForList(
            "SELECT * FROM login WHERE id = ?", userId.intValue());
        System.out.println("用户数据: " + users);
        
        // 查询所有购物车数据
        List<Map<String, Object>> allCartItems = jdbcTemplate.queryForList(
            "SELECT c.*, g.name FROM cart c JOIN goods g ON c.sku_id = g.id");
        System.out.println("所有购物车数据: " + allCartItems);
        
        // 获取所有商品
        List<Map<String, Object>> allGoods = jdbcTemplate.queryForList("SELECT * FROM goods");
        System.out.println("商品表数据样本(前5条): " + 
            (allGoods.size() > 5 ? allGoods.subList(0, 5) : allGoods));
        System.out.println("商品总数: " + allGoods.size());
        
        // 创建直接可用的购物车项目
        List<CartItem> directCartItems = new ArrayList<>();
        for (Map<String, Object> item : cartItems) {
            CartItem cartItem = new CartItem();
            cartItem.setId(((Number)item.get("id")).longValue());
            cartItem.setUserId(((Number)item.get("user_id")).longValue());
            cartItem.setSkuId(((Number)item.get("sku_id")).longValue());
            cartItem.setCount((Integer)item.get("count"));
            cartItem.setSelected((Boolean)item.get("checked"));
            
            // 设置一些缺省值
            cartItem.setPrice(BigDecimal.valueOf(99));
            cartItem.setName("商品 " + cartItem.getSkuId());
            cartItem.setPicture("https://img.picui.cn/free/2025/03/20/67dbcea0b6f32.png");
            
            directCartItems.add(cartItem);
        }
        
        // 返回所有调试数据
        Map<String, Object> result = new HashMap<>();
        result.put("cartItems", cartItems);
        result.put("users", users);
        result.put("allCartItems", allCartItems);
        result.put("directCartItems", directCartItems);
        result.put("goodsCount", allGoods.size());
        return Result.success(result);
    }

    @DeleteMapping
    public ResponseEntity<String> deleteCartItems(
            @RequestParam("userId") Long userId,
            @RequestBody List<Long> ids) {
        try {
            cartService.deleteCartItems(userId, ids);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/merge")
    public ResponseEntity<String> mergeCart(
            @RequestBody List<CartItem> items,
            @RequestParam("userId") Long userId) {
        try {
            cartService.mergeCart(items, userId);
            return ResponseEntity.ok("合并成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("合并失败: " + e.getMessage());
        }
    }

    // 更新购物车商品选中状态
    @PostMapping("/check")
    public ResponseEntity<String> updateCartItemChecked(
            @RequestParam("userId") Long userId,
            @RequestBody Map<String, Object> params) {
        try {
            // 获取前端传递的skuId和selected值
            Long skuId = Long.parseLong(params.get("skuId").toString());
            Boolean selected = Boolean.parseBoolean(params.get("selected").toString());
            
            System.out.println("更新购物车商品选中状态，用户ID: " + userId + ", 商品ID: " + skuId + ", 选中状态: " + selected);
            
            // 更新购物车选中状态
            int rows = jdbcTemplate.update(
                "UPDATE cart SET checked = ? WHERE user_id = ? AND sku_id = ?",
                selected, userId, skuId);
            
            if (rows > 0) {
                System.out.println("更新成功");
                return ResponseEntity.ok("更新成功");
            } else {
                System.out.println("更新失败，找不到对应的购物车商品");
                return ResponseEntity.badRequest().body("更新失败: 找不到对应的购物车商品");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("更新失败: " + e.getMessage());
        }
    }
    
    // 更新购物车全选状态
    @PostMapping("/checkAll")
    public ResponseEntity<String> updateCartAllChecked(
            @RequestParam("userId") Long userId,
            @RequestBody Map<String, Object> params) {
        try {
            // 获取前端传递的selected值
            Boolean selected = Boolean.parseBoolean(params.get("selected").toString());
            
            System.out.println("更新购物车全选状态，用户ID: " + userId + ", 选中状态: " + selected);
            
            // 更新该用户所有购物车商品的选中状态
            int rows = jdbcTemplate.update(
                "UPDATE cart SET checked = ? WHERE user_id = ?",
                selected, userId);
            
            System.out.println("更新了 " + rows + " 条购物车记录");
            return ResponseEntity.ok("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("更新失败: " + e.getMessage());
        }
    }
}